#include "stdafx.h"
#include "..\headers\InputSystemPrereq.h"

namespace ne{

JoyStick::JoyStick(OIS::JoyStick* joystick):m_joystick(joystick),m_buttons(nullptr),m_lastButtons(nullptr),m_pov(0),m_lastPov(0) {
	m_numButtons = (int)joystick->getJoyStickState().mButtons.size();	// Different joysticks will have different ammount of buttons
	m_buttons = new bool[m_numButtons];
	m_lastButtons = new bool[m_numButtons];
	std::fill(m_buttons, m_buttons + m_numButtons, false);
	std::fill(m_lastButtons, m_lastButtons + m_numButtons, false);
	m_joystick->setEventCallback(this);
}
JoyStick::~JoyStick(void){
	if (m_buttons){
		delete[] m_buttons;
		m_buttons = nullptr;
	}
	if (m_lastButtons){
		delete[] m_lastButtons;
		m_lastButtons = nullptr;
	}
}

void JoyStick::Capture(){
	memcpy(m_lastButtons, m_buttons, sizeof(bool)*m_numButtons);
	m_lastPov = m_pov;
	m_joystick->capture();
}

bool JoyStick::IsButtonDown(int button){
	if (button < m_numButtons && button >= 0){
		return m_buttons[button];
	}
	return false;
}

bool JoyStick::IsButtonPressed(int button){
	if (button < m_numButtons && button >= 0){
		if (!m_lastButtons[button] && m_buttons[button]){
			return true;
		}
	}
	return false;
}

bool JoyStick::IsButtonReleased(int button){
	if (button < m_numButtons && button >= 0){
		if (m_lastButtons[button] && !m_buttons[button]){
			return true;
		}
	}
	return false;
}

float JoyStick::GetAxis(int axis){
	int numAxis = (int)m_joystick->getJoyStickState().mAxes.size();
	if (axis >= 0 && axis < numAxis){
		return (float)m_joystick->getJoyStickState().mAxes[axis].abs / (float)OIS::JoyStick::MAX_AXIS;
	}
	return 0.0f;
}

int JoyStick::GetPov(){
	return m_joystick->getJoyStickState().mPOV->direction;
}

bool JoyStick::IsPovDown(int pov){
	return pov == m_pov ? true : false;
}

bool JoyStick::IsPovPressed(int pov){
	if (pov == m_pov && pov != m_lastPov){
		return true;
	}
	return false;
}

bool JoyStick::IsPovReleased(int pov){
	if (pov != m_pov && pov == m_lastPov){
		return true;
	}
	return false;
}

bool JoyStick::povMoved(const OIS::JoyStickEvent& e, int pov){
	m_pov = e.state.mPOV[pov].direction;
	return false;
}

bool JoyStick::axisMoved(const OIS::JoyStickEvent& e, int axis){
	//TODO
	return false;
}

bool JoyStick::sliderMoved(const OIS::JoyStickEvent& e, int slider){
	//TODO
	return false;
}

bool JoyStick::buttonPressed(const OIS::JoyStickEvent& e, int button){
	if (button < m_numButtons && button >= 0){
		m_buttons[button] = true;
	}
	return false;
}

bool JoyStick::buttonReleased(const OIS::JoyStickEvent& e, int button){
	if (button < m_numButtons && button >= 0){
		m_buttons[button] = false;
	}
	return false;
}

}